import router from '@/routes'
import { defineStore } from "pinia"
import store from '@/store'

import { asyncRoutes } from "@/routes/modules/asyncRoutes"
import { staticRoutes } from "@/routes/modules/staticRoutes"
import { TStore } from '../typings';
import { TRoute } from "@/routes/typings";
import mittBus, { MittBusKeys } from '@/mittBus'
import { TRole } from '@/typings/role';

function filterRoutes(routes: TRoute.MenuPropsList, parent: TRoute.MenuProps | null = null): TRoute.MenuPropsList {
    const result = [] as TRoute.MenuPropsList
    for (const route of routes) {
        // 如果定义 IsHide 不获取
        if (!(route.children && route.children.length > 0) && route.meta && route.meta.isHide) {
            continue
        }
        if (parent === null && route.path === '/' && route.children && route.children.length > 0) {
            result.push(...filterRoutes(route.children, route))
        }
        else {
            const tmpRoute = { ...route } as TRoute.MenuProps
            // if(parent){
            if (route.path[0] === '/') {
                tmpRoute.path = route.path
            } else {
                if (parent) {
                    tmpRoute.path = parent.path !== '/' ? `${parent.path}/${route.path}` : `/${route.path}`
                } else {
                    tmpRoute.path = `/${route.path}`
                }
            }
            // console.log(tmpRoute.path, route.path, parent)
            // }
            if (tmpRoute.children) {
                tmpRoute.children = filterRoutes(tmpRoute.children, tmpRoute)
            }
            result.push(tmpRoute)
        }
    }
    return result
}

/** 路由全局状态 */
export const useRouteStore = defineStore('route-store', {
    state: (): TStore.RouteStore => ({
        // 默认路由配置
        staticRoutes: staticRoutes,
        // 动态路由，根据角色变化
        asyncRoutes: [],
        removeRoute: []
    }),
    getters: {
        constantRoutes(state: TStore.RouteStore): TRoute.MenuPropsList {
            return state.staticRoutes.concat(state.asyncRoutes)
        },
        constantMenus(state: TStore.RouteStore): TRoute.MenuPropsList {
            return filterRoutes(state.staticRoutes.concat(state.asyncRoutes), null)
        }
    },
    actions: {
        changeRoles(roles: Array<string> | undefined) {
            if (this.removeRoute.length > 0) {
                for (const removeFn of this.removeRoute) {
                    removeFn()
                }
                this.removeRoute = []
                this.asyncRoutes = []
            }
            this.asyncRoutes = roles && roles.length > 0 ? asyncRoutes : []
            if (this.asyncRoutes && this.asyncRoutes.length > 0) {
                for (const route of this.asyncRoutes) {
                    this.removeRoute.push(router.addRoute(route))
                }
            }
        }
    }
})

/** Setup 外使用 */
export function useRouteStoreHook() {
    return useRouteStore(store)
}

/** 处理相关事件 */
mittBus.on(MittBusKeys.LOGIN_ROLES_SUCCESS, (roles: any) => {
    const routeStore = useRouteStoreHook()
    const roleNames = (roles as TRole.RoleList).map(role => role.name)
    routeStore.changeRoles(roleNames)
})

mittBus.on(MittBusKeys.LOGOUT_SUCCESS, () => {
    const routeStore = useRouteStoreHook()
    routeStore.changeRoles([])
})